package cn.itsource.ymcc.service.impl;

import cn.itsource.ymcc.domain.Department;
import cn.itsource.ymcc.mapper.DepartmentMapper;
import cn.itsource.ymcc.service.IDepartmentService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author whale.chen
 * @since 2024-06-06
 */
@Service
public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper, Department> implements IDepartmentService {

    @Autowired
    DepartmentMapper departmentMapper;
    @Override
    public List<Department> deptTree() {
        //首先查询出所以department并将其缓存到HashMap中
        Map<Long, Department> map = new HashMap<>();

        List<Department> list = departmentMapper.selectList(new LambdaQueryWrapper<Department>().select(Department::getId, Department::getName, Department::getParentId));
        //遍历list存入map中
        for (Department department : list) {
            map.put(department.getId(), department);
        }
        List<Department> deptTree = new ArrayList<>();
        for (Department department : list) {
            //如果父节点为空，则直接添加到根节点
            if (department.getParentId() == null) {
                deptTree.add(department);
            } else {
                //如果父节点不为空，则将父节点的子节点添加到父节点中
                Department parent = map.get(department.getParentId());
                if (parent != null) {
                    parent.getChildren().add(department);
                }
            }
        }
        System.out.println(deptTree);
        return deptTree;
    }
}
